package logic

import (
	"context"
	"errors"
	"novel-mgr1/model"

	"novel-mgr1/userrpc/internal/svc"
	"novel-mgr1/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type BooksAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBooksAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BooksAddLogic {
	return &BooksAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 加入书架
func (l *BooksAddLogic) BooksAdd(in *userrpc.BooksAddRequest) (*userrpc.BooksAddResponse, error) {
	// todo: add your logic here and delete this line
	var findUser model.User
	err := findUser.FindUserById(model.DB, in.Uid)
	if err != nil {
		return nil, err
	}
	if findUser.ID == 0 {
		return nil, errors.New("请登录")
	}
	var findNovel model.Novel
	err = findNovel.FindNovelById(model.DB, in.Nid)
	if err != nil {
		return nil, err
	}
	if findNovel.ID == 0 {
		return nil, errors.New("作品不存在")
	}

	var findBooks model.Books
	err = findBooks.FindBooksById(model.DB, in)
	if err != nil {
		return nil, err
	}
	if findBooks.ID != 0 {
		return nil, errors.New("已加入")
	}

	books := model.Books{
		Uid: in.Uid,
		Nid: in.Nid,
	}

	err = books.BooksAdd(model.DB)
	if err != nil {
		return nil, errors.New("加入失败")
	}
	return &userrpc.BooksAddResponse{
		BooksId: int64(books.ID),
	}, nil
}
